package com.sen.gateway.auth;

import cn.hutool.core.net.URLEncoder;
import com.sen.common.common.bo.User;
import com.sen.common.common.constrant.CommonConstrant;
import com.sen.common.common.util.JacksonUtils;
import lombok.SneakyThrows;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.Charset;

/**
 * 认证成功处理类
 * @author esjiang
 */
public class Oauth2AuthSuccessHandler implements ServerAuthenticationSuccessHandler {
    @SneakyThrows
    @Override
    public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {
        MultiValueMap<String, String> headerValues = new LinkedMultiValueMap(4);
        /** 客户端模式只返回一个clientId */
        OAuth2Authentication oauth2Authentication = (OAuth2Authentication)authentication;
        User user = ((User) oauth2Authentication.getUserAuthentication().getPrincipal());
        headerValues.add(CommonConstrant.X_PEOPLE_HEADER, URLEncoder.createDefault().encode(JacksonUtils.toJSONString(user.getPeopleInfo()), Charset.forName("utf-8")));
        headerValues.add(CommonConstrant.X_USER_HEADER,URLEncoder.createDefault().encode(user.getUsername(),Charset.forName("utf-8")));
        headerValues.add(CommonConstrant.X_TENANT_HEADER,user.getSysAccount().getTenantCode());
        ServerWebExchange exchange = webFilterExchange.getExchange();
        ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate()
                .headers(h -> {
                    h.addAll(headerValues);
                })
                .build();

        ServerWebExchange build = exchange.mutate().request(serverHttpRequest).build();
        return webFilterExchange.getChain().filter(build);
    }
}
